import type {
  ActionType,
  ColumnsState,
  ProColumns,
} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import * as c from '@/services/consts';
import * as api from '@/services/ticket';
import * as utils from '@/utils/utils';
import { ReloadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Badge, Popconfirm, Radio, Space, Tag } from 'antd';
import TicketForm from './components/TicketForm';
import dayjs from 'dayjs';

const dateFormat = 'YYYY-MM-DD';
const renderBadge = (count: number, active = false) => {
  return (
    <Badge
      count={count}
      overflowCount={9999}
      showZero
      style={{
        marginTop: -4,
        marginLeft: 2,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

const UserLogList: React.FC = () => {
  // const [formBatchChangeVisible, setFormBatchChangeVisible] = useState<boolean>(false);
  const [formTicketVisible, setFormTicketVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.Ticket | undefined>(undefined);
  const [filterType, setFilterType] = useState<string | undefined>('unlog');
  const [selectIds, setSelectIds] = useState<any[]>([]);
  // const [controlState, setControlState] = useState<number>(0);

  const [statusStatMenus, setStatusStatMenus] = useState<any[]>([]);
  const [dateStatMenus, setDateStatMenus] = useState<any[]>([]);
  const [ticketDate, setTicketDate] = useState<string | undefined>('-');
  const [ticketStatus, setTicketStatus] = useState<string | undefined>('0');

  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    id: {
      show: false,
    },
    appendInfo: {
      show: false,
    },
    deviceid: {
      show: false,
    },
  });

  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductOptions } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductOptions: model.getProductOptions,
    }),
  );

  const loadDateStatMenus = async () => {
    var result = await api.dateCount({
      type: filterType,
      status: ticketStatus,
    });
    let datas: API.DateStat[] = [];
    let totalCount = 0;
    if (result && result.success) {
      datas = result.data ?? [];
      totalCount = result.totalCount ?? 0;
    }
    let items: any[] = [
      getTabItem('全部', '-', totalCount, ticketDate === '-'),
    ];
    for (let i = 0; i < 7; i++) {
      let nowDay = dayjs().add(-i, 'days');
      let nowStr = nowDay.format(dateFormat);
      let dayCount = 0;
      for (let k = 0; k < datas.length; k++) {
        if (nowStr == dayjs(datas[k].date).format(dateFormat)) {
          dayCount = datas[k].count;
          break;
        }
      }
      items.push(
        getTabItem(
          nowDay.format('MM/DD'),
          nowStr,
          dayCount,
          nowStr == ticketDate,
        ),
      );
    }

    setDateStatMenus(items);
  };

  const loadStatusStatMenus = async () => {
    var result = await api.statusCount({ type: filterType });
    let totalCount = 0;
    let datas: API.StatusStat[] = [];
    if (result && result.success) {
      datas = result.data ?? [];
      totalCount = result.totalCount ?? 0;
    }
    let items: any[] = [
      getMenuItem('全部', '-1', totalCount, ticketStatus === '-1'),
    ];
    c.TicketStatusOptions.forEach((element) => {
      let count = 0;
      for (let i = 0; i < datas.length; i++) {
        if (datas[i].status == element.value) {
          count = datas[i].count;
          break;
        }
      }
      items.push(
        getMenuItem(element.label, element.value.toString(), count, false),
      );
    });

    setStatusStatMenus(items);
  };

  const getTabItem = (
    display: string,
    key: string,
    count: number,
    selected: boolean,
  ) => {
    return {
      tab: (
        <span>
          {display} {renderBadge(count, selected)}
        </span>
      ),
      key: key,
    };
  };

  const getMenuItem = (
    display: string,
    key: string,
    count: number,
    selected: boolean,
  ) => {
    return {
      label: (
        <span>
          {display} {renderBadge(count, selected)}
        </span>
      ),
      key: key,
    };
  };

  useEffect(() => {
    loadDateStatMenus();
  }, [ticketStatus, ticketDate, filterType]);

  useEffect(() => {
    loadStatusStatMenus();
  }, [filterType]);

  const reload = () => {
    loadDateStatMenus();
    loadStatusStatMenus();
    actionRef.current?.reload();
  };

  // const handleFormBatchChangeSubmit = async (info:string|undefined) => {
  //   // var ticket = {
  //   //   ...current,
  //   //   ...record};
  //   // const result = await api.updateInfo({ id: ticket.id, status:ticket.status, handlerInfo: "" });
  //   // if (result.success) {
  //   //   setCurrent(undefined);
  //   //   setFormProblemVisible(false);
  //   //   actionRef.current?.reload();
  //   // }
  // };

  const handleFormTicketSubmit = () => {
    setCurrent(undefined);
    setFormTicketVisible(false);
    actionRef.current?.reload();
  };

  const handleBatchClose = async (
    onCleanSelected: any,
    info: string | undefined,
  ) => {
    const result = await api.closelist({ keys: selectIds, info: info });
    if (result && result.success) {
      setSelectIds([]);
      onCleanSelected();
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.Ticket>[] = [
    {
      title: '状态',
      align: 'center',
      width: 100,
      dataIndex: 'status',
      sorter: true,
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.status == 0 ? (
              <Tag color="error">待处理</Tag>
            ) : record.status == 1 ? (
              <Tag color="blue">处理中</Tag>
            ) : record.status == 2 ? (
              <Tag>关闭</Tag>
            ) : // record.status == 3 ? <Tag color='cyan'>延时处理</Tag> :
            // record.status == 4 ? <Tag color='orange'>研发处理</Tag> :
            record.status == 5 ? (
              <Tag color="success">完成</Tag>
            ) : (
              <Tag>未知</Tag>
            )}
            {record.existNewReply ? <Tag color="error">有新回复</Tag> : ''}
          </>
        );
      },
      // valueEnum: {
      //   0: {
      //     text: '待处理',
      //     status: 'Error',
      //   },
      //   1: {
      //     text: '处理中',
      //     status: 'Processing',
      //   },
      //   2: {
      //     text: '关闭',
      //     status: 'Default',
      //   },
      // },
    },
    {
      title: 'ID',
      dataIndex: 'id',
      width: 160,
      sorter: true,
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      search: false,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '产品',
      dataIndex: 'productId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: true,
        options: getProductOptions(false),
      },
    },
    {
      title: '类型',
      align: 'center',
      width: 100,
      dataIndex: 'type',
      sorter: true,
      search: false,
      renderText: (val: string) => {
        return val.toUpperCase();
      },
    },
    {
      title: '联系邮箱',
      dataIndex: 'contactEmail',
      sorter: true,
    },
    {
      title: '用户留言',
      dataIndex: 'subject',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        return (
          <>
            {record.subject && <span>{record.subject} </span>}
            {!record.subject && record.content && (
              <span>{record.content} </span>
            )}
            {record.logFile && (
              <span>
                <a href={record.logFile} target="_blank">
                  [诊断日志]
                </a>
              </span>
            )}
          </>
        );
      },
    },
    {
      title: '设备ID',
      dataIndex: 'deviceid',
      sorter: true,
    },
    // {
    //   title: '版本',
    //   dataIndex: 'ver',
    //   sorter: true,
    //   search:false,
    // },
    {
      title: '提交时间',
      align: 'center',
      dataIndex: 'createTime',
      sorter: true,
      search: false,
      width: 150,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.createTime);
      },
    },
    {
      title: '附加信息',
      dataIndex: 'appendInfo',
      valueType: 'textarea',
      search: false,
      ellipsis: true,
    },
    // {
    //   title: '处理信息',
    //   dataIndex: 'handlerInfo',
    //   valueType: 'textarea',
    //   ellipsis: true,
    //   search:false,
    // },
    {
      title: '处理人',
      dataIndex: 'resolvedBy',
      sorter: true,
      width: 100,
      search: false,
      // renderText: (_, record) => {
      //   let text = '';
      //   if (record.handlerUsername) {
      //     text += record.handlerUsername;
      //   }
      //   if (record.handlerName) {
      //     text += `(${record.handlerName})`;
      //   }
      //   return text;
      // },
    },
    {
      title: '更新时间',
      align: 'center',
      dataIndex: 'updateTime',
      sorter: true,
      search: false,
      width: 150,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.updateTime);
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 60,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('ticket_updatestatus')) {
          //   if (record.status == c.TickctStatus.Open) {
          //     cmps.push(
          //       <Popconfirm
          //         key="updatestatus"
          //         title="确定要将状态更新为 处理中 吗?"
          //         onConfirm={async () => {
          //           await handleUpdateStatus(
          //             record.id,
          //             c.TickctStatus.Processing,
          //           );
          //         }}
          //       >
          //         <a>处理</a>
          //       </Popconfirm>,
          //     );
          //   } else if (record.status == c.TickctStatus.Processing) {
          //     cmps.push(
          //       <Popconfirm
          //         key="updatestatus"
          //         title="确定要关闭吗?"
          //         onConfirm={async () => {
          //           await handleUpdateStatus(record.id, c.TickctStatus.Close);
          //         }}
          //       >
          //         <a>关闭</a>
          //       </Popconfirm>,
          //     );
          //   }

          cmps.push(
            <a
              key="updatestatus2"
              onClick={async () => {
                setCurrent(record);
                setFormTicketVisible(true);
              }}
            >
              处理
            </a>,
          );

          // cmps.push(
          //   <a
          //     key="updatestatus"
          //     onClick={async () => {
          //       setCurrent(record);
          //       setFormProblemVisible(true);
          //     }}
          //   >
          //     处理问题
          //   </a>,
          // );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: false,
          // setting: false,
          density: false,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        search={{
          labelWidth: 80,
          defaultCollapsed: false,
          span: 4,
        }}
        toolbar={{
          multipleLine: true,
          menu: {
            type: 'inline',
            activeKey: ticketStatus,
            items: statusStatMenus,
            onChange: (key) => {
              setTicketStatus(key as string);
            },
          },
          tabs: {
            activeKey: ticketDate,
            items: dateStatMenus,
            onChange: (key) => {
              setTicketDate(key);
            },
          },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          toolbarDoms.push(
            <Space>
              <Radio.Group defaultValue="d" buttonStyle="solid">
                <Radio.Button
                  value="a"
                  onClick={() => {
                    setFilterType(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                <Radio.Button
                  value="b"
                  onClick={() => {
                    setFilterType('email');
                  }}
                >
                  EMAIL
                </Radio.Button>
                <Radio.Button
                  value="c"
                  onClick={() => {
                    setFilterType('support');
                  }}
                >
                  SUPPORT
                </Radio.Button>
                <Radio.Button
                  value="d"
                  onClick={() => {
                    setFilterType('unlog');
                  }}
                >
                  非LOG
                </Radio.Button>
                <Radio.Button
                  value="e"
                  onClick={() => {
                    setFilterType('log');
                  }}
                >
                  LOG
                </Radio.Button>
              </Radio.Group>
              ,
              <a
                onClick={() => {
                  reload();
                }}
              >
                <ReloadOutlined />
              </a>
            </Space>,
          );
          return toolbarDoms;
        }}
        rowSelection={{
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>

            <span>
              <Popconfirm
                key="batchChange1"
                title="确定要批量关闭无效问题？"
                onConfirm={async () => {
                  handleBatchClose(onCleanSelected, '批量关闭无效问题');
                }}
              >
                <a>无效问题</a>
              </Popconfirm>
            </span>

            <span>
              <Popconfirm
                key="batchChange2"
                title="确定要批量关闭重复问题？"
                onConfirm={async () => {
                  handleBatchClose(onCleanSelected, '批量关闭重复问题');
                }}
              >
                <a>重复问题</a>
              </Popconfirm>
            </span>
          </Space>
        )}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: ['15', '30', '60', '100', '200'],
          hideOnSinglePage: true,
        }}
        params={{
          filterType: filterType,
          filterDate: ticketDate,
          status: ticketStatus,
        }}
        request={api.list}
      />

      {/* <BatchChangeForm
        visible={formBatchChangeVisible}
        onSubmit={handleFormBatchChangeSubmit}
        onCancel={() => {
          setFormBatchChangeVisible(false);
        }}
      /> */}

      <TicketForm
        visible={formTicketVisible}
        onSubmit={handleFormTicketSubmit}
        current={current}
        onCancel={() => {
          setCurrent(undefined);
          setFormTicketVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default UserLogList;
